<?php
declare (strict_types = 1);

namespace app\home\controller;

use app\admin\model\Category;
use app\common\controller\Frontend;
use app\common\exception\Http;
use org\Htt;
use think\facade\Db;
use think\facade\View;

class Doc extends Frontend
{
    public function initialize()
    {
        parent::initialize();
        global $userinfo;
        $userinfo = $this->visitor->info;
        View::assign('uid', $userinfo['id']);
        $this->_mod = Db::name('doc_con');
        $action = request()->get('action');
        View::assign('action', $action);

        //文档分类，自动查询，以便列表页和其他页面调用
        $cate = Db::name('category')->where(array('pid' => 0, 'status' => 1))->order('ordid')->select()->toArray();
        $cate_arr=[];
        $tcate_arr=[];
        foreach ($cate as $key => $value) {
            $cate_arr[$key] = $value;
            $tcate = Db::name('category')->where(array('pid' => $value['id'], 'status' => 1))->order('ordid')->select()->toArray();
            $cate_arr[$key]['tcate'] = $tcate;
        }

        View::assign('cate', $cate_arr); //所有分类，首页只取前八个大类


    }

    public  function pdfview(){
        return \view();
    }
    public function doccate(){
            return view();
    }

    public function doc_share() {
        $seoconfig['title'] = "文档上传";
        //获取一级文档分类
        $catlist = Db::name('category')->where(array('pid' => 0))->select();
        View::assign('catlist', $catlist);
        $mod = Db::name('doc_con');
        global $userinfo;
        $uid = $userinfo['id'];
        if ($uid < 1 || $uid == '') {
            return redirect('/home/user/login');
        }
        if (request()->isPost()) {
            $type = request()->param('type');
            $data = request()->param();
            if ($data['oldname'] == '') {
                return fail(0,'请上传文件！');
                $this->error('请上传文件！');
            }
            if ($data['cid'] < 1) {
                return fail(0,'请选择分类！');
                $this->error('请选择分类！');
            }
            $data['score'] = intval($data['score']);
            if ($data['tags'] == '') {
                $data['tags'] = getcatename('doc', $data['cid']);
            } else {
                $data['tags'] = $data['tags'] . ',' .getcatename('doc', $data['cid']);
            }
            $tagarr = explode(',', $data['tags']);
            $tagarr = array_unique($tagarr);
            $data['tags'] = implode(',', $tagarr);
            $data['intro'] = request()->param('intro');
            $fileinfo = explode('.', $data['fileurl']);
            $data['filename'] = $fileinfo[0];
            if ($type == 'add') {
                $data['model'] = config('web_config.web_model');
                $data['status'] = config('web_config.web_switch.doc_con');
                $data['uid'] = $uid;
                if (doc_title_exists($data['title'])) {
                    return fail(0,'该标题已经存在！');
                }
                unset($data['type']);
                unset($data['Filedata']);
                unset($data['tid']);
                unset($data['like1']);
                $data['create_time'] =time();
                $mod->save($data);
                return success(1,'操作成功');
            }
        } else {
            $uploadimgurl = url('doc/ajax_upload');
            View::assign('uploadimgurl', $uploadimgurl);
            return view();
        }
    }

    public function ajax_getsubcate() {
        $id = request()->param('id');
        $return = Db::name('category')->field('id,name')->where(array('pid'=>$id,'status'=>1))->select();
        if ($return) {
            return success(1,'操作成功',$return,'');
        } else {
            return success(0,'操作失败',$return,'');
        }
    }

    public function ajax_upload(){
        $file = request()->file('Filedata');  //这里‘file’是你提交时的name
        $paths = 'doc';
        $info = [
            'ext'=>$file->extension(),
            'size' => $file->getSize(),    // 文件名：读书顶个鸟用.jpg
            'name' => $file->getFilename(),    // 文件MINE：image/jpeg
            'mime' => $file->getMime(),
            'oldname'=>$file->getOriginalName(),
            'hash'=>$file->hash()
        ];
        try{
            validate(['goodFile' => [     //goodFile是你自定义的键名，目的是为了对check里数组中的
                'fileSize' =>50*1024*1024,//goodFile字段值进行验证;允许文件大小
                'fileExt'  => array('doc','docx','xls','xlsx','pptx','ppt','wps','et','pdf','txt'),  //允许的文件后缀
            ]])->check(['goodFile'=>$file]);//也就是对上传的$file进行验证

            $saveName = \think\facade\Filesystem::disk('public')->putFile( $paths, $file,
                function () use ($file){
                    switch ('date') {
                        case 'date':
                            $fileName = date('YmdHis').rand(1,9999).rand(1,9999);
                            break;
                        // 此项即为：保留原始文件名+日期方式
                        case 'original':
                            $fileName = str_replace('.'.$file->getOriginalExtension(),'',$file->getOriginalName().date('YmdHis'));
                            break;
                        default:
                            $fileName = uniqid();
                            break;
                    }
                    return $fileName;
                });//保存文件名
            $f_name = explode('/',$saveName);
            $info['name'] = end($f_name);
            $info['convert_key'] = $paths;
            $arr = ['status' => 1, 'msg' => '成功', 'info' => $info];
            return json($arr);   				//返回标准json格式
        }catch (\Exception $e) {
            return fail( 0, '上传失败!' . $e->getMessage());
        }
    }




    public function doclist(){
        global $userinfo;
        $id = request()->param('id')?request()->param('id'):0;
        $idarr = getcateallid($id);
        $catearr = '';
        if(is_array($idarr)){
            foreach ($idarr as $key =>$value){
                if($key == 0){
                    $catearr = $value['id'];
                } else{
                    $catearr.=','.$value['id'];
                }
            }
        } else{
            $catearr = $idarr;
        }

        // 根据ID获取分类
        $map['id'] = $id;
        $pid = Db::name('category')->where($map)->value('pid');//id的上级id
        $spid= Db::name('category')->where($map)->value('spid');//id的上级id
        if($pid >= 0){
            if ($pid == 0) {
                $map1['pid']=$id;
                $map1['status']=1;
                $tcate=Db::name('category')->where($map1)->select();//所有二级分类
            } else {
                $map1['pid']=$pid;
                $map1['status']=1;
                $tcate=Db::name('category')->where($map1)->select();//取上级分类
            }
        }
        $tcateid =0;
        $thcate =[];
        if($spid != ''){
            $count=substr_count($spid, '|');
            if($count == 2){
                //三级分类 得到二级分类id，然后该二级分类下面所有三级分类
                $tcateid = Db::name('category')->where(array('id'=>$pid,'status'=>1))->getField('id');
                $thcate  = Db::name('category')->where(array('pid'=>$tcateid,'status'=>1))->select();
            } else{
                //二级分类，本身的二级分类id，然后得到下面的三级分类
                $tcateid = $id;
                $thcate = Db::name('category')->where(array('pid'=>$id,'status'=>1))->select();
            }
        }

        View::assign('pid',$pid);
        View::assign('tcate',$tcate);
        View::assign('tcateid',$tcateid);
        View::assign('thcate',$thcate);

        //排序
        $cname = request()->param('c');
        if ($id <= 0 && !$cname ) {
            $navname='全部文档';
        }
        if (!$cname) {
            $cname = $order = 'newdoc';
        }
        switch ($cname){
            case 'newdoc':
                $navname='最新文档';
                $order='create_time desc';
                break;
            case 'hotdoc':
                $navname='热门文档';
                $order='hits desc';
                break;
            case 'downdoc':
                # 没有下载量字段
                $navname='热门文档';
                $order='id desc';
                break;
            default:
                $order = 'create_time desc';
                break;
        }

        View::assign('search_order', $cname);
        View::assign('order', $order);
        View::assign('catearr',$catearr);
        View::assign('cname',$cname);
        View::assign('navname',$navname);
        View::assign('id',$id);
        return view();
    }

    public function doccon() {
        $view = request()->param('view') ;
        //点击增加1
        $id =request()->param('id') ;
        Db::name('doc_con')->where(array('id' => $id))->inc('hits', 1);
        //获得文档信息
        global $userinfo;
        $uid = $userinfo['id'];
        $uid = $userinfo['id']?$userinfo['id']:1;
        $score = getuserscore($uid);
        View::assign('score', $score);
        $map['id'] = $id;
        $info = Db::name('doc_con')->find($id);
        View::assign('info',$info);
        if (!$info) {
            return '操作失败';
        }
        if (!$info || $info['status'] < 1) {
            return return_jump_tip(0, '该文档已关闭或者未审核', '/');
        }
        $similar = similardoc($id, 10);
        $samecatedoc = samecatedoc($id);
        $mapraty['itemid'] = $id;
        $mapraty['typeid'] = 1;
        $info['tags'] = explode(',', $info['tags']);
        foreach ($info['tags'] as $key => $value) {
            $maptag['name'] = $value;
            $tagarr[] = Db::name('tag')->where($maptag)->find();
        }

        $intro = $info['intro'];
        View::assign('intro', $intro);
        View::assign('info', $info);
        View::assign('uid', $userinfo['id']);
        //谁下载过
        $downnum = Db::name('itemlog')->where(array('itemid' => $id, 'type' => 1, 'typeid' => 1))->count();
        $tuijiannum = Db::name('itemlog')->where(array('itemid' => $id, 'type' => 3, 'typeid' => 1))->count();
        $xhnum = Db::name('itemlog')->where(array('itemid' => $id, 'type' => 2, 'typeid' => 1))->count();
        $hasxh = '';
        $hastj = '';
        if (Db::name('itemlog')->where(array('itemid' => $id, 'type' => 2, 'typeid' => 1, 'uid' => $uid))->find()) {
            $hasxh = 1;

        }
        if (Db::name('itemlog')->where(array('itemid' => $id, 'type' => 3, 'typeid' => 1, 'uid' => $uid))->find()) {
            $hastj = 1;

        }
        View::assign('hasxh', $hasxh);
        View::assign('hastj', $hastj);

        $downuser = $this->downdoc($id, 5); //谁下载过
        View::assign('downnum', $downnum);
        View::assign('tuijiannum', $tuijiannum);
        View::assign('xhnum', $xhnum);
        View::assign('downuser', $downuser);
        View::assign('id', $id);//文档的ID
        return view();

    }

    //谁下载过
    public function downdoc($id, $num) {
        $map['itemid'] = $id;
        $map['typeid'] = 1;
        $map['type'] = 1;
        //$data=D('itemlog')->where($map)->select();
        $data = Db::name('itemlog')->where($map)->limit($num)->select();
        return $data;
    }

    //删除我的文档 - wf
    public function delmydoc() {

        $id= request()->param('id');;
        $mod = Db::name('doc_con');
        $map['id'] = $id;
        if ($mod->where($map)->delete()) {
            return success(1,'删除成功');
        } else {
            return fail(0,'删除失败');

        }
    }

    public function showdownload($name = '下载', $method = 'download') {
        $id =  request()->param('id');
        global $userinfo;
        $uid = $userinfo['id']?$userinfo['id']:1;
        $userscore = getuserscore($uid);
        $info = Db::name('doc_con')->where(array('id' => $id))->find();
        if ($uid == '') {
            $url = url('user/login');
            $scoreinfo = '您还未登陆，<a href="'.$url.'">点我登陆！</a>';
        } else {
            if ($uid == $info['uid'] || $uid == 1) {
                $url = url('doc/download', array('id' => $id, 'down' => 'yes'));
                $scoreinfo = '您可以无限制'.$name.'此文档！';
            } else {
                $map['uid'] = $uid;
                $map['itemid'] = $info['id'];
                $map['typeid'] = 1;
                $map['type'] = 1; //表示下载
                if (Db::name('itemlog')->where($map)->value('id') > 0) {
                    $url = url('doc/' . $method, array('id' => $id, 'down' => 'yes'));
                    $scoreinfo = '您已经'.$name.'过此文档，再次'.$name.'免费！';
                } else {
                    $userscore = $userscore - $info['score'];
                    if ($userscore < 0) {
                        $url = 'javascript:void(0);';
                        $scoreinfo = '您的积分不足以进行此次'.$name.'！';
                    } else {
                        $url = url('doc/' . $method, array('id' => $id, 'down' => 'yes'));
                        $scoreinfo = '恭喜！购买成功'.$name.'！';
                    }
                }
            }
        }
        $fileurl = Db::name('doc_con')->where(array('id' => $id))->find();
        $file = $fileurl['fileurl'];
        if ($fileurl['model'] == 1) {
            if (!file_exists('./' . config('wkcms_attach_path') . "docswf/data/" . $file)) {
                $http = new Http();
                $http->curlDownload('http://www.wkcms.net/data/upload/doc_con/' . $file, './' . C('wkcms_attach_path') . 'doc_con/' . $file);
            }
        }
        View::assign('url', $url);
        View::assign('scoreinfo', $scoreinfo);
        View::assign('userscore', $userscore);
        View::assign('info', $info);
        $response = View::fetch();
        return success(1, '', $response);
    }

    public function download() {
        $id = request()->param('id');
        $info = Db::name('doc_con')->field('html,fileurl')->find($id);
        $url =docfile($info['html'],$info['fileurl']);
//        download_url($url);
//        var_dump($url);exit;
//        $hh = 'https://ceyi.oss-cn-hangzhou.aliyuncs.com/result.pdf';
        header('Location: '.$url);
//        exit;
    }


}